package com.zhangst.bbs.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangst.bbs.dao.BaseDaoI;
import com.zhangst.bbs.domain.User;
import com.zhangst.bbs.page.DataList;
import com.zhangst.bbs.service.UserServiceI;
import com.zhangst.bbs.util.GenericUtil;

@Service("userService")
public class UserServiceImpl implements UserServiceI{

	private BaseDaoI<User> userDao;
	
	
	
	public BaseDaoI<User> getUserDao() {
		return userDao;
	}
	
	@Autowired
	public void setUserDao(BaseDaoI<User> userDao) {
		this.userDao = userDao;
	}

	@Override
	public void add(User user) {
		userDao.save(user);
		
	}

	@Override
	public void edit(User user) {
		userDao.update(user);
		
	}

	@Override
	public void del(User user) {
		userDao.delete(user);
	}

	@Override
	public DataList getUsers(int page, int rows) {
		if(page<=0){
			page=1;
		}
		if(rows<=0){
			rows=10;
		}
		DataList list = new DataList();
		list.setPage(page);
		list.setNum(rows);
		String hql = "from User";
		list.setRows(userDao.find(hql, page, rows));
		Long total = userDao.count("select count(*)"+hql);
		list.setTotal(total);
		return list;
	}

	@Override
	public User login(User u) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("psw", GenericUtil.MD5(u.getPsw()));
		params.put("username", u.getUsername());
		User user = userDao.get("from User t where t.username = :username and t.psw = :psw", params);
		return user;
	}

	@Override
	public User getUser(String username) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", username);
		User user = userDao.get("from User t where t.username = :username", params);
		return user;
	}

}
